/**
 * 细粒度权限控制
 * 2020/07/12
 */
const URL = require('url');
const TEACHER_ROLE = ['admin','org','school','teacher'];
const ORG_ROLE = ['admin','org','school'];
const ADMIN_ROLE = ['admin'];

const roles = {
  student: {common: TEACHER_ROLE},
  class: {common: TEACHER_ROLE},
  teacher: {common: ORG_ROLE, list: TEACHER_ROLE},
  chapter: {common: ORG_ROLE, list: TEACHER_ROLE},
  series: {common: ORG_ROLE, list: TEACHER_ROLE},
  course: {common: ORG_ROLE, list: TEACHER_ROLE, open: TEACHER_ROLE},
  file: {common: ORG_ROLE, list: TEACHER_ROLE},
  notify: {common: TEACHER_ROLE},
  oss: {common: ORG_ROLE},
  org: {common: ADMIN_ROLE}
};

const permission = (req, res, next) => {
  const router = getRouterName(req);
  const method = getMethod(req);
  if (!roles.hasOwnProperty(router)) {
    return res.send({code: 10000, message: '权限校验失败'});
  }

  const need_role = getRouterRole(router, method);
  const user_role = req.decode.roles[0];
  for (const role of need_role) {
    if (user_role === role) return next();
  }
  return res.send({code: 10000, message: '权限校验失败'});
};

const getRouterName = req => {
  const pathname = URL.parse(req.url).pathname;
  return pathname.split('/')[1];
};

const getRouterRole = (router, method) => {
  if (method && roles[router].hasOwnProperty(method)) return roles[router][method];
  return roles[router].common
};

/**
 * @param req
 * @returns {string|boolean} method
 */
const getMethod = req => {
  const pathname = URL.parse(req.url).pathname;
  const method = pathname.split('/')[2];
  if (method) return method;
  return false;
};

module.exports = {
  permission
};
